<template>

  <div class="book-container">
    <el-row>

      <template>
        <span>图书类别：</span>
        <el-select v-model="categoryList.id" clearable placeholder="请选择" @change="changeProduct(categoryList)">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </template>

      <div style="margin-top:20px" />
      <span>
        <template>
          <!-- <div class="input-group"> -->
          <el-input v-model="searchStr" type="text" class="form-control" style="width:460px;" clearable>
            <el-select slot="prepend" v-model="slectedSearchType.id" size="medium" style="width:100px;">
              <el-option
                v-for="item in searchType"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <template slot="append">

              <el-button style="width:100px; background-color:#409eff;color:white" @click="headleSearch()">搜索</el-button>

            </template>
          </el-input>
          <!-- </div> -->
          <!-- <div style="margin-top:20px" /> -->

        </template>
      </span>
    </el-row>
    <el-divider />
    <el-button type="danger" @click="judegeIsSelection(1)">批量下架</el-button>
    <el-button type="success" @click="judegeIsSelection(0)">批量上架</el-button>
    <!-- <el-button type="danger" @click="ConfirmSelectionDelete">批量删除</el-button> -->
    <el-button type="warning" @click="handeleOutExportExcel">导出</el-button>
    <el-table
      :data="bookList"
      style="width: 100%"
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <template slot="empty">
        <p>{{ dataText }}</p>
      </template>
      <el-table-column type="selection" />
      <el-table-column prop="id" label="id" sortable width="80" />

      <el-table-column
        prop="deleted"
        label="上架状态"
        width="120"
        align="center"
        :filters="options"
        :filter-method="filterHandler"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.deleted === 1" type="info">已下架</el-tag>
          <el-tag v-else-if="scope.row.deleted === 0" type="success">上架中</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="bookName" label="书名" align="center" />
      <el-table-column prop="author" label="作者" align="center" />
      <el-table-column prop="repositoryNum" label="库存" align="center" />
      <el-table-column prop="price" label="价格" sortable align="center" />
      <el-table-column prop="sales" label="销量" sortable align="center" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleDetail(scope.$index, scope.row)">详细</el-button>
          <!-- <el-button size="mini" type="danger" @click="ConfirmDelete(scope.$index, scope.row)">删除</el-button> -->
          <el-button v-if="scope.row.deleted === 1" size="mini" type="success" plain @click="handleGrounding(scope.$index, scope.row)">上架</el-button>
          <el-button v-if="scope.row.deleted === 0" size="mini" type="danger" plain @click="handleUngrounding(scope.$index, scope.row)">下架</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        :current-page.sync="getBookForm.current"
        :page-size="getBookForm.size"
        layout="prev, pager, next, jumper"
        :total="getBookForm.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </div>
</template>
<script>

import { getBookList, getCategory, getBooksByCid, deleteBookById, handleSelectedBooks, handleGrounding, getBookDetailById, searchBooks } from '@/utils/book.js'
import { outExportExcel } from '@/api/exportData.js'
export default {
  name: 'BookIndex',
  data() {
    return {
      value: '',
      bookList: [],
      hasData: false,
      dataText: '',
      // 被选中的订单数组,有handleSelectionChange处理
      selectionBooksId: [],
      // 被选中的图书列表
      selectionBooks: [],
      // dialog的显示消失控制
      dialogTableVisible: true,
      // 整个dialog的form表单都不能修改
      dialogFormDisable: true,
      dialogBookForm: null,
      getBookForm: {
        current: 1,
        size: 20,
        orderType: 0,
        total: null
      },
      searchBookForm: {
        current: 1,
        size: 20,
        type: 1,
        orderType: 0
      },
      // category相关
      categoryList: [],
      searchType: [
        {
          id: 1,
          name: '按书名'
        },
        {
          id: 2,
          name: '按作者'
        },
        {
          id: 3,
          name: '按Id'
        }
      ],
      slectedSearchType: {
        id: 1,
        name: '按书名'
      },
      searchStr: '',
      getBookByCategoryForm: {
        current: 1,
        size: 20,
        cId: '',
        orderType: 0,
        total: null
      },
      getCategoryForm: {
        current: 1,
        size: 999,
        cId: '',
        orderType: 0,
        total: null
      },
      categoryHasData: false,
      categoryDataText: '',
      // selectedcategoryId: '',
      // 书籍上架状态
      deletedFilter: '',
      options: [
        {
          value: 0,
          text: '上架中'
        },
        {
          value: 1,
          text: '已下架'
        }
      ],
      groundingOrUngrounding: '下架'
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getBookList(this.getBookForm).then(res => {
        if (res.object.records && res.object.records.length > 0) {
          this.categoryHasData = true
        } else {
          // this.$message('暂无订单数据')
          this.dataText = '暂无数据'
        }
        this.bookList = res.object.records
        this.getBookForm.total = res.object.total
      })
      getCategory(this.getCategoryForm).then(res => {
        if (res.object.records && res.object.records.length > 0) {
          this.categoryHasData = true
        } else {
          // this.$message('暂无订单数据')
          this.categoryDataText = '暂无数据'
        }
        this.categoryList = res.object.records
        // this.getCategoryForm.total = res.object.total
      })
    },
    // 获取select框中选中的内容
    changeProduct(event) {
      this.searchStr = '' // 清空搜索框内容
      this.getBookForm.current = 1
      this.searchBookForm.current = 1
      this.getBookByCategoryForm.current = 1
      this.getBookByCategoryForm.cId = event.id
      this.doGetBookBycategoryForm()
    },
    doGetBookBycategoryForm() {
      if (this.getBookByCategoryForm.cId === '') {
        this.getList()
      } else {
        getBooksByCid(this.getBookByCategoryForm).then(res => {
          if (res.object.records && res.object.records.length > 0) {
            this.categoryHasData = true
          } else {
          // this.$message('暂无订单数据')
            this.dataText = '暂无数据'
          }
          this.bookList = res.object.records
          this.getBookForm.total = res.object.total
        })
      }
    },
    // 选择框改变
    handleSelectionChange(val) {
      const arr = []
      const selectionBooksArr = []
      val.forEach(element => {
        arr.push(element.id)
        selectionBooksArr.push(element)
      })
      this.selectionBooksId = arr
      this.selectionBooks = selectionBooksArr
    },
    // 弹出图书详细框
    handleDetail(index, obj) {
      // 跳转到bookdetail路由
      this.$router.push(`/book/detail/${obj.id}`)
    },
    enableDialogForm() {
      this.dialogFormDisable = false
    },
    submitBookUpdate() {
      this.$message('book update ')
    },
    handleSizeChange() {

    },
    // 翻页操作
    handleCurrentChange(val) {
      if (this.searchStr) { // 如果搜索框有内容
        this.searchBookForm.current = val
        this.doSearch()
      } else if (this.getBookByCategoryForm.cId) { // 如果种类选择框有内容
        this.getBookByCategoryForm.current = val
        this.doGetBookBycategoryForm()
      } else {
        this.getBookForm.current = val
        getBookList(this.getBookForm).then(res => {
          if (res.object.records && res.object.records.length > 0) {
            this.categoryHasData = true
          } else {
          // this.$message('暂无订单数据')
            this.dataText = '暂无数据'
          }
          this.bookList = res.object.records
          this.getBookForm.total = res.object.total
        })
      }
    },
    // 多选删除警告
    ConfirmSelectionDelete() {
      this.$confirm('此操作将永久删除这些数据, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deletedSelectedBooks()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 单独删除警告
    ConfirmDelete(scopeIndex, scopeRow) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(scopeIndex, scopeRow)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除一条
    handleDelete(scopeIndex, scopeRow) {
      deleteBookById(scopeRow.id).then(res => {
        // if (res.code === 200) {
        //   this.$message.success('删除成功')
        // } else {
        //   this.$message.error('删除失败')
        // }
        this.getList()
      })
    },
    // 批量删除
    deletedSelectedBooks() {
      handleSelectedBooks(1, this.selectionBooksId).then(() => {
        this.getList()
      })
    },
    // 判断是否空选
    judegeIsSelection(deleted) {
      if (this.selectionBooksId.length === 0) {
        this.$alert('请选择至少一条商品', '警告', {
          confirmButtonText: '确定',
          type: 'warning'
        })
      } else {
        var judgeIsUnGrounding = 0
        var judgeIsGrounding = 0
        this.selectionBooks.forEach(element => {
          if (element.deleted === 1) { // 只要选中的商品中有一个是已下架的，就把judgeIsUnGrounding设置为1
            judgeIsUnGrounding = 1
          } else { // 只要选中的商品中有一个是正在上架状态，就把judgeUnGrounding设置为1
            judgeIsGrounding = 1
          }
        })
        if (deleted === 0) {
          if (judgeIsUnGrounding === 1) { // 判断：如果选中的商品中至少有一个是已下架的，就可以执行批量上架操作。
            this.ConfirmSelectionGrounding()
          } else {
            this.$alert('请选择至少一个已下架的商品', '警告', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
        } else { // 判断：如果选中的商品中至少有一个是已上架的，就可以执行批量下架操作。
          if (judgeIsGrounding === 1) {
            this.ConfirmSelectionUnGrounding()
          } else {
            this.$alert('请选择至少一个已上架的商品', '警告', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
        }
      }
    },
    // 批量上架警告
    ConfirmSelectionGrounding() {
      this.$confirm('确定上架这些商品？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.groundingselectionBooks()
        this.$message({
          type: 'success',
          message: '上架成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消上架'
        })
      })
    },
    // 批量下架警告
    ConfirmSelectionUnGrounding() {
      this.$confirm('确定下架这些商品？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.unGroundingselectionBooks()
        this.$message({
          type: 'success',
          message: '下架成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消下架'
        })
      })
    },
    // 批量上架
    groundingselectionBooks() {
      handleSelectedBooks(2, this.selectionBooksId).then(this.getList())
    },
    // 批量下架
    unGroundingselectionBooks() {
      handleSelectedBooks(3, this.selectionBooksId).then(this.getList())
    },
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    // 上架一条操作
    handleGrounding(value, row, column) {
      row.deleted = 0
      handleGrounding(row).then(res => {
        this.$message.success('上架成功')
      }).catch()
    },
    // 下架一条操作
    handleUngrounding(value, row, column) {
      row.deleted = 1
      handleGrounding(row).then(res => {
        this.$message.success('下架成功')
      }).catch()
    },
    // 搜索操作
    headleSearch() {
      this.categoryList.id = '' // 清空种类选择框
      this.getBookForm.current = 1
      this.searchBookForm.current = 1
      this.doSearch()
    },
    doSearch() {
      if (this.slectedSearchType.id === 3) { // 根据id查一本书
        if (this.searchStr === '') { // 根据id查询如果输入值为空则会404，所以需要判断。根据书名、作者查询输入值为空则会返回所有书籍
          this.getList()
        } else {
          getBookDetailById(this.searchStr).then(res => {
            this.bookList = []
            this.bookList.push(res.object)
          }).catch(error => {
            console.log(error)
          })
        }
      } else { // 模糊搜索可能搜索出多本书
        searchBooks(this.searchBookForm, this.slectedSearchType.id, this.searchStr).then(res => {
          this.bookList = res.object.records
          this.getBookForm.total = res.object.total
        }).catch(error => {
          console.log(error)
        })
      }
    },
    handeleOutExportExcel() {
      const tableHeader = ['ID', '图书名称', '作者', '出版社', '价格', '销量', '库存', '状态']
      const tableKey = ['id', 'bookName', 'author', 'publisher', 'price', 'sales', 'repositoryNum', 'deleted']
      outExportExcel(
        tableHeader,
        tableKey,
        this.bookList
      )
    }
  }
}
</script>

<style scoped lang='scss'>
.book-container {
  margin: 20px;
}
.block {
  margin-top: 20px;
  text-align: center;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.select {
  position: absolute;
    top: 0px;
    left: 410px;
    border: 2px solid #ff2832;
    border-left: 0px solid #dedede;
    width: 92px;
    height: 36px;
    // font: 16px/36px "Microsoft Yahei";
    color: #969696;
    padding: 0 0 0 14px;
    // cursor: pointer;
    background-color: #f6f6f6;
}
</style>
